<?php

namespace Beerus\Modules\BrandRights\Controllers;

use Biz\model\brandRights\BrandPackageRightsConfig;
use Biz\service\BrandRights\BrandRightsSourceService;
use Encore\Admin\Grid;
use Biz\tools\helper\Common;
use Illuminate\Http\Request;
use App\Pockets\GridDataModel;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Biz\model\brand\BrandPackage;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use Illuminate\Support\MessageBag;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Encore\Admin\Grid\Displayers\Actions;
use Biz\model\brandRights\BrandRightsSource;
use Biz\service\BrandRights\BrandPackageService;
use Illuminate\Contracts\Foundation\Application;
use Biz\service\BrandRights\BrandPackageRightsConfigService as packConfig;

/**
 * Description: 基础权益管理
 * Created by PhpStorm.
 * User: 玉坤
 * Date: 2021/12/21
 * Time: 18:17
 */
class PackConfigController extends Controller
{
    public const  PAGE_SIZE = 20;

    /**
     * 获取列表
     *
     * @param Request $request
     * @param Content $content
     *
     * @return Content
     */
    public function index(Request $request, Content $content): Content
    {
        Admin::script($this->auditScript());
        $params = $request->all();
        $page_size = $params['per_page'] ?? self::PAGE_SIZE;
        $params['per_page'] = $page_size;
        $where = $this->_getWhere($params);
        $list = BrandPackageService::getList($where);
        unset($where['LIMIT']);
        $count = BrandPackageService::selectCount($where);
        $gridModel = new GridDataModel($list, $count, [
            'perPage' => $page_size,
        ]);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function ($filter) {
                    $filter->disableIdFilter();
                    // 在这里添加字段过滤器
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('id', '套餐id');
                        $filter->equal('pack_type', '类型')
                            ->select(BrandPackage::$packTypeDesc);
                        $filter->equal('type', '套餐类别')
                            ->select(BrandPackage::$types);
//                        $filter->equal('stat_type', '统计类型')
//                            ->select(BrandPackage::$statPackTypes);
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('package_name', '套餐名称')
                            ->placeholder('套餐名称');
                        $package_status = [
                            BrandPackage::STATUS_NORMAL => "启用",
                            BrandPackage::STATUS_OFF => "停用",
                        ];
                        $filter->equal('package_status', '套餐状态')
                            ->select($package_status)
                            ->default(BrandPackage::STATUS_NORMAL);
                    });
                    $filter->expand();//默认展开
                });
                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->column('id', '套餐id')->sortable();
                $grid->column('package_name', '套餐名称');
                $grid->column('pack_type', '套餐类型')
                    ->using(BrandPackage::$packTypeDesc, '自定义')->label(
                        [
                            BrandPackage::PACK_TYPE_NORMAL => 'default',
                            BrandPackage::PACK_TYPE_PLUS => 'default',
                            BrandPackage::PACK_TYPE_PRO => 'default',
                            BrandPackage::PACK_CERTIFIED => 'warning',
                            BrandPackage::PACK_HIGH_CERTIFIED => 'info',
                            BrandPackage::PACK_CERTIFIED_PLUS => 'success',
                            BrandPackage::PACK_HIGH_CERTIFIED_PLUS => 'primary',
                            BrandPackage::PACK_HIGH_CERTIFIED_SIMPLE => 'danger'
                        ]
                    );
                $grid->column('type', '套餐类别')
                    ->using(BrandPackage::$types, '')->label(
                        [
                            BrandPackage::TYPE_ONLINE => 'danger',
                            BrandPackage::TYPE_OFFLINE => 'warning',
                        ]
                    );
                $grid->column('meal_time', '套餐天数')->display(function ($meal_time) {
                    return $meal_time;
                });
//                $grid->column('stat_type', '统计类型')
//                    ->using(BrandPackage::$statPackTypes, '无')->label(
//                        [
//                            BrandPackage::STAT_PACK_TRY => 'default',
//                            BrandPackage::STAT_PACK_CERTIFIED_PLUS => 'success',
//                            BrandPackage::STAT_PACK_HIGH_CERTIFIED_PLUSY => 'danger'
//                        ]
//                    );
                $grid->column('cal_price', '原价');
                $grid->column('discount_price', '优惠价');
                $grid->column('admin_id', '操作人')->display(function () {
                    if (!$this->admin_id) {
                        return '-';
                    } else {
                        return Admin::user()->find($this->admin_id)->name;
                    }
                });

                $package_status = [
                    BrandPackage::STATUS_NORMAL => "启用",
                    BrandPackage::STATUS_OFF => "停用",
                ];

                $grid->column('package_status', '状态')->using(
                    $package_status
                    , '未知')->label([
                    BrandPackage::STATUS_NORMAL => 'success',
                    BrandPackage::STATUS_OFF => 'danger',
                    BrandPackage::STATUS_DELETE => 'danger',
                ]);

                $grid->setActionClass(Actions::class);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableView();
                    $status = $actions->row->package_status;
                    if ($status != BrandPackage::STATUS_DELETE) {
//                        $html_delete = ' <a class="fa fa-trash" data-state="'
//                            . BrandPackage::STATUS_DELETE . '" data-id="'
//                            . $actions->row->id . '" href="javascript:void(0);" style="margin-right: 5px">
//                                    <span class="glyphicon" aria-hidden="true">删除</span></a>';
//                        $actions->append($html_delete);
                        $source_html_edit
                            = ' <a class="fa fa-edit"  href="pack/'
                            . $actions->row->id . '/sourceList" style="margin-right: 5px">
                                    <span class="glyphicon" aria-hidden="true">权益编辑</span></a>';
                        $actions->prepend($source_html_edit);
                        $html_copy = ' <a class="fa fa-copy" data-id="'
                            . $actions->row->id . '" href="javascript:void(0);" style="margin-right: 5px">
                                    <span class="glyphicon" aria-hidden="true">复制套餐</span></a>';
                        $actions->prepend($html_copy);
                    } else {
                        $actions->disableEdit();
                    }
                });
            }
        );
//        $tab = new Tab();
//        $tab->add('套餐管理列表', $grid->render(), true);
        $content->row($grid);

        return $content
            ->header('套餐管理列表')
            ->description(' ')
            ->breadcrumb(['text' => '套餐管理列表', 'url' => '/BrandRights/pack']);
    }


    /**
     * 获取查询条件
     *
     * @param $params
     *
     * @return array
     */
    private function _getWhere($params): array
    {
        $id = $params['id'] ?? null;
        $packageName = $params['package_name'] ?? '';
        $page = $params['page'] ?? 1;
        $per_page = $params['per_page'] ?? 20;
        $status = isset($params['package_status']) && $params['package_status'] != '' ? $params['package_status'] : null;
        $pack_type = $params['pack_type'] ?? null;
        $type = $params['type'] ?? null;
        //$stat_type = $params['stat_type'] ?? null;
        if ($id) {
            $where['id'] = $id;
        }
        if ($packageName) {
            $where['package_name[~]'] = $packageName . '%';
        }
        if ($pack_type) {
            $where['pack_type'] = $pack_type;
        }
        if ($type) {
            $where['type'] = $type;
        }
//        if ($stat_type) {
//            $where['stat_type'] = $stat_type;
//        }
        $where['LIMIT'] = [
            ($page - 1) * $per_page,
            $per_page,
        ];

        $where['package_status'] = is_null($status) ? [BrandPackage::STATUS_NORMAL, BrandPackage::STATUS_OFF] : $status;

        $where['ORDER'] = [
            'id' => 'DESC'
        ];
        if (isset($params['_sort']["column"], $params['_sort']["type"])) {
            $where['ORDER'] = [
                $params['_sort']["column"] => strtoupper($params['_sort']["type"]),
            ];
        }
        return $where;
    }

    /**
     * 更改权益状态
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function audit(Request $request): JsonResponse
    {
        try {
            $params = $request->all();

            $rule = [
                'id' => 'required|int',
                'package_status' => 'required|int',
            ];
            $validator_msg = Common::validatorRule($rule, $params);
            if ($validator_msg !== true) {
                throw  new \Exception($validator_msg);
            }
            $admin_id = Admin::user()->id;
            $data['id'] = $params['id'];
            $data['admin_id'] = $admin_id;
            $data['package_status'] = $params['package_status'];
            $info = BrandPackageService::getInfo($params['id']);
            if (!$info) {
                throw new \Exception('不存在的活动');
            }
            BrandPackageService::audit($data);
            $success = [
                'title' => '操作成功',
                'code' => 1,
            ];
        } catch (\Exception $e) {
            $success = [
                'title' => '操作失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }

        return response()->json($success);
    }


    public function copyPackage($id)
    {
        try {
            $rule = [
                'id' => 'required|int',
            ];
            $validatorMsg = Common::validatorRule($rule, ['id' => $id]);
            if ($validatorMsg !== true) {
                throw  new \Exception($validatorMsg);
            }
            $admin_id = Admin::user()->id;
            $copyResult = BrandPackageService::copy($id, $admin_id);
            if (!$copyResult) {
                throw  new \Exception('操作失败');
            }
            $message = [
                'title' => '操作成功',
                'code' => 1,
            ];

        } catch (\Exception $e) {
            $message = [
                'title' => '操作失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }
        return response()->json($message);
    }

    /**
     * 更改权益状态js 删除
     *
     * @return string
     */
    private function auditScript()
    {
        return <<<SCRIPT

        $('.fa-copy').unbind('click').click(function(){
            var id= $(this).data('id');
            let url = '/admin/BrandRights/pack/copy/'+ id
            let params = {id:id}
            swal({
                    title: "确认复制本套餐吗？",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "确认",
                    showLoaderOnConfirm: true,
                    cancelButtonText: "取消",
                    preConfirm: function() {
                    //ajax
                        $.ajax({
                            method: 'post',
                            url: url,
                            data: params,
                            success: function (e) {
                                if (e.code == 1) {
                                swal({
                                    title: e.title,
                                    type: "warning",
                                });
                                    setTimeout(function () {
                                        $.pjax.reload('#pjax-container');
                                    }, 1000);
                                } else {
                                    toastr.error(e.title, null, {
                                        timeOut : 3000
                                    }); 
                                }
                            }
                        });
                    //ajax-end
                    }
            });
        });


        $('.fa-trash').unbind('click').click(function(){
            var id= $(this).data('id');
            var status=$(this).data('state');
            let url = '/admin/BrandRights/pack/audit'
            let params = {id:id,package_status:status}
            swal({
                    title: "确认提交吗？",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "确认",
                    showLoaderOnConfirm: true,
                    cancelButtonText: "取消",
                    preConfirm: function() {
                    //ajax
                        $.ajax({
                            method: 'post',
                            url: url,
                            data: params,
                            success: function (e) {
                                if (e.code == 1) {
                                swal({
                                    title: e.title,
                                    type: "warning",
                                });
                                    setTimeout(function () {
                                        $.pjax.reload('#pjax-container');
                                    }, 1000);
                                } else {
                                    toastr.error(e.title, null, {
                                        timeOut : 3000
                                    }); 
                                }
                            }
                        });
                    //ajax-end
                    }
            });
        });
       
SCRIPT;
    }

    /**
     * 编辑
     *
     * @param           $id
     * @param Content $content
     *
     * @return Content|RedirectResponse
     */
    public function edit($id, Content $content)
    {
        if (!$id) {
            admin_error('参数错误！', 'warning');
        }
        //编辑wiki
        $baseInfo = BrandPackage::getById($id);
        if (!$baseInfo) {
            $error = new MessageBag([
                'title' => '信息不存在或已删除',
            ]);
            return back()->with(compact('error'));
        }
        $baseForm = new Form($baseInfo);
        $baseForm->disableReset();
        $baseForm->text('package_name', '套餐名称')->required();
        $baseForm->select('type', '套餐类别')->options(BrandPackage::$types,
            '未知')->value($baseInfo['type'])->required();
//        $baseForm->select('stat_type', '统计类型')->options(BrandPackage::$statPackTypes,
//            '未知')->value($baseInfo['stat_type']);
        $baseForm->text('meal_time', '有效期')->required();
        $baseForm->text('cal_price', '原价格')->readonly();
        $baseForm->text('discount_price', '优惠价')->required();
        $baseForm->select('package_status', '状态')->options([
            BrandPackage::STATUS_NORMAL => "启用",
            BrandPackage::STATUS_OFF => "停用",
        ],
            '未知')->value($baseInfo['package_status'])->required();
        $baseForm->text('remark', '备注');
        $baseForm->hidden('id');


        $baseForm->confirm('确定更新吗？');
        $baseForm->action('/admin/BrandRights/pack/save');

        return $content
            ->header('修改')
            ->description(' ')
            ->breadcrumb(
                ['text' => '套餐管理列表', 'url' => '/BrandRights/pack'],
                ['text' => '套餐修改']
            )
            ->row($baseForm);
    }

    /**
     * 保存
     *
     * @param Request $request
     *
     * @return Application|RedirectResponse|Redirector
     */
    public function save(Request $request)
    {
        try {
            $params = $request->all();
            $rules = [
                "package_name" => 'required|string',
                //"pack_type" => 'required|integer',
                "type" => 'required|integer',
                "package_status" => 'required|integer',
                //"stat_type" => 'required|integer',
                "meal_time" => 'required|integer',
                "cal_price" => 'required|numeric',
                "discount_price" => 'required|numeric',
            ];

            //更新
            $info = BrandPackage::getById($params['id']);
            if (!$info || !is_array($info)) {
                throw new \Exception('套餐不存在！');
            }
            //校验参数
            $res_msg = Common::validatorRule($rules, $params);
            if ($res_msg !== true) {
                throw new \Exception($res_msg);
            }
            $data = [
                "package_name" => $params["package_name"],
                //"pack_type" => $params["pack_type"],
                "type" => $params["type"],
                "package_status" => $params["package_status"],
                //"stat_type" => $params["stat_type"],
                "meal_time" => $params["meal_time"],
                "cal_price" => $params["cal_price"],
                "price" => $params["discount_price"],
                "discount_price" => $params["discount_price"],
                "remark" => $params["remark"] ?? '',

            ];
            $success = new MessageBag([
                'title' => '成功',
            ]);
            //更新
            $this->updateData($params['id'], $data);
//            return redirect('/admin/BrandRights/pack/' . $params['id'] . '/edit')->with(compact('success'))->withInput();

        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage(),
            ]);
            return back()->with(compact('error'))->withInput();
        }
        return redirect('/admin/BrandRights/pack')->with(compact('success'));
    }

    /**
     * 更新
     *
     * @param $id
     * @param $data
     *
     * @return void
     */
    private function updateData($id, $data): void
    {
        $where['id'] = $id;
        BrandPackage::updateData($data, $where);
    }

    /**
     * 新增
     *
     * @param $data
     *
     * @return void
     */
    private function insertData($data): void
    {
        $data['admin_id'] = Admin::user()->id;
        BrandPackage::insertData($data);
    }


    /**
     * 新增
     *
     * @param Content $content
     * @param Form $form
     *
     * @return Content
     */
    public function create(Content $content, Form $form): Content
    {
        $form->disableReset();
        $form->text('package_name', '套餐名称')->required();
        $form->select('type', '套餐类别')->options(BrandPackage::$types,
            '未知')->default(BrandPackage::TYPE_OFFLINE);
//        $form->select('stat_type', '统计类型')->options(BrandPackage::$statPackTypes,
//            '未知')->default(BrandPackage::STAT_PACK_TRY);
        $form->text('meal_time', '套餐天数')->default(365)->required();
        $form->text('cal_price', '套餐总价')->readonly()->placeholder('套餐总价由所选权益计算生成');
        $form->text('discount_price', '促销价格')->required();
        $form->text('remark', '备注');

        $form->confirm('确定创建吗？');

        $form->action('/admin/BrandRights/pack/createSave');

        return $content
            ->header('新增')
            ->description(' ')
            ->breadcrumb(
                ['text' => '套餐管理列表', 'url' => '/BrandRights/pack'],
                ['text' => '新增']
            )
            ->row($form);
    }


    /**
     * 新增保存
     *
     * @param Request $request
     *
     * @return Application|RedirectResponse|Redirector
     */
    public function createSave(Request $request)
    {
        try {
            $params = $request->all();
            $rules = [
                "package_name" => 'required|string',
                "type" => 'required|integer',
                //"pack_type" => 'required|integer',
                //"stat_type" => 'required|integer',
                "meal_time" => 'required|integer',
                //"price"          => 'required|numeric',
                "discount_price" => 'required|numeric',
            ];
            //校验参数
            $res_msg = Common::validatorRule($rules, $params);
            if ($res_msg !== true) {
                throw new \Exception($res_msg);
            }

            $pack_type = BrandPackage::getNewPackType($params['type']);

            if (!$pack_type) {
                throw new \Exception('生成pack_type失败！');
            }

            $data = [
                "package_name" => $params["package_name"],
                "pack_type" => $pack_type,
                "type" => $params["type"],
                //"stat_type" => $params["stat_type"],
                "meal_time" => $params["meal_time"],
                "cal_price" => $params["cal_price"] ?? 0.00,
                "price" => $params["discount_price"],
                "discount_price" => $params["discount_price"],
                "remark" => $params["remark"] ?? '',
                "package_status" => BrandPackage::STATUS_NORMAL
            ];

            $success = new MessageBag([
                'title' => '成功',
            ]);
            $this->insertData($data);
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage(),
            ]);
            return back()->with(compact('error'))->withInput();
        }
        return redirect('/admin/BrandRights/pack')->with(compact('success'));
    }

    /**
     * 权益配置列表
     *
     * @param           $id
     * @param Content $content
     *
     * @return Content|RedirectResponse
     */
    public function sourceList(Request $request, $id, Content $content)
    {
        Admin::script($this->setRightsSourceScript());
        if (!$id) {
            admin_error('参数错误！', 'warning');
        }
        //获取套餐配置权益ids
        $params = $request->all();
        $rightsWhere = $this->_rightsWhere($params);
        $baseInfo = packConfig::getPackConfigList($id, $rightsWhere);

        if (!$baseInfo) {
            $error = new MessageBag([
                'title' => '信息不存在或已删除',
            ]);
            return back()->with(compact('error'));
        }
        $list = $baseInfo['sources_list'];
        $packInfo = $baseInfo['pack_info'];
        $gridModel = new GridDataModel($list, 0, []);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $packInfo) {
                $grid->filter(function ($filter) {
                    $filter->disableIdFilter();
                    // 在这里添加字段过滤器
                    $filter->column(1 / 3, function ($filter) {
                        $allSourceRights
                            = BrandRightsSourceService::getAll([
                            'id',
                            'rights_title'
                        ]);
                        $allSourceRightsKv = array_column($allSourceRights,
                            'rights_title', 'id');
                        $filter->equal('id', '权益id')
                            ->select($allSourceRightsKv);
                        $filter->equal('rights_name', '权益英文标识')
                            ->placeholder('权益英文标识');
                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('rights_group', '运营分类')
                            ->select(BrandRightsSource::RIGHTS_GROUPS);
                        $filter->equal('rights_business_scene', '适用业务')
                            ->select(BrandRightsSource::FIT_BUSINESS_SCENES)
                            ->default(BrandRightsSource::BUSINESS_SCENE_BRAND);
                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('rights_type', '权益类型')
                            ->select(BrandRightsSource::RIGHTS_TYPE_ARR);
                        $filter->equal('data_status', '状态')
                            ->select(BrandRightsSource::STATUS_ARR);
                    });
                    $filter->expand();//默认展开
                });
                $grid->disableCreateButton();
                $grid->disablePagination();
                //$grid->disableFilter();
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', '权益id');
                $grid->column('rights_title', '权益名称');
                $grid->column('rights_name', '权益英文名称')->copyable();
                $grid->column('rights_type', '权益类型')->using(
                    BrandRightsSource::RIGHTS_TYPE_ARR
                    , '未知')->label([
                    BrandRightsSource::RIGHTS_TYPE_OPEN => 'warning',
                    BrandRightsSource::RIGHTS_TYPE_LIMIT_NUM => 'info',
                    BrandRightsSource::RIGHTS_TYPE_NUM => 'success',
                    BrandRightsSource::RIGHTS_TYPE_OTHER => 'default',
                ]);

                $grid->column('rights_group', '运营分类')->display(function (
                    $rights_group
                ) {
                    return BrandRightsSource::RIGHTS_GROUPS[$rights_group] ??
                        '';
                });

                $grid->column('rights_data', "数量")->display(function (
                    $rights_data,
                    $column
                ) {
                    if ($this->rights_type
                        == BrandRightsSource::RIGHTS_TYPE_LIMIT_NUM || $this->rights_type == BrandRightsSource::RIGHTS_TYPE_NUM
                    ) {
                        if ($this->status == BrandPackageRightsConfig::STATUS_NORMAL) {
                            return $column->editable();
                        } else {
                            return '';
                        }

                    }

                    return '/';
                });

                $grid->column('price', '单价');

                $grid->column('rights_desc', '权益描述');

                $grid->column('sort_weight', '排序');

                // 设置text、color、和存储值
                $states = [
                    'on' => [
                        'value' => 1,
                        'text' => '启用',
                        'color' => 'primary'
                    ],
                    'off' => [
                        'value' => 2,
                        'text' => '停用',
                        'color' => 'default'
                    ],
                ];

                $grid->column('status', "状态")->switch($states);
                $grid->disableActions();

            }
        );
        $content->row($grid);

        return $content
            ->header('套餐权益配置列表')
            ->description($packInfo['package_name'] . ",ID:" . $packInfo['id'])
            ->breadcrumb(
                ['text' => '套餐管理列表', 'url' => '/BrandRights/pack'],
                ['text' => '套餐权益配置列表']
            );
    }


    private function _rightsWhere($params = [])
    {
        $type = $params['rights_type'] ?? null;
        $rights_id = $params['id'] ?? null;
        $rights_name = $params['rights_name'] ?? null;
        $rights_group = $params['rights_group'] ?? null;
        $rights_business_scene = $params['rights_business_scene'] ?? null;
        $data_status = isset($params['data_status']) && $params['data_status'] != '' ? $params['data_status'] : null;
        $where = [];
        if ($type) {
            $where['rights_type'] = $type;
        }
        if ($rights_id) {
            $where['id'] = $rights_id;
        }
        if ($rights_name) {
            $where['rights_name[~]'] = $rights_name . '%';
        }
        if ($rights_group) {
            $where['rights_group'] = $rights_group;
        }
        if ($rights_business_scene) {
            $where['rights_business_scene'] = $rights_business_scene;
        }
        if (!is_null($data_status)) {
            $where['data_status'] = $data_status;
        }
        return $where;
    }

    /**
     * 套餐权益保存
     *
     * @param           $package_id
     * @param           $sourceId
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function sourceSave(
        $package_id,
        $sourceId,
        Request $request
    ): JsonResponse {
        $params = $request->all();
        //获取套餐权益
        try {
            $adminId = Admin::user()->id;
            packConfig::updatePackSource($package_id, $sourceId, $params, $adminId);
            if (isset($params['status'])) {
                if ($params['status'] == BrandPackageRightsConfig::STATUS_ON) {
                    $message = '权益开启成功，如果是数量型权益请设置数量';
                } else {
                    $message = '权益关闭成功';
                }

            } elseif (isset($params['value'])) {
                $message = '修改权益数量成功';
            } else {
                $message = '操作成功';
            }
            $success = [
                'message' => $message,
                'status' => true,
            ];
        } catch (\Exception $e) {
            $success = [
                'message' => '操作失败,' . $e->getMessage(),
                'status' => false,
            ];
        }
        return response()->json($success);
    }


    private function setRightsSourceScript()
    {
        return <<<SCRIPT
    var obj;
    $('.grid-switch-status').unbind('bootstrapSwitch').bootstrapSwitch({
        size:'mini',
        onText: '开启',
        offText: '关闭',
        onColor: 'primary',
        offColor: 'default',
        onSwitchChange: function(event, state){
            obj = $(this);
            $(this).val(state ? 1 : 2);
            var key = $(this).data('key');
            var value = $(this).val();
            var _status = true;
            var titleArr = new Array();
            titleArr[1] = '确认为当前套餐开启该权益吗？';
            titleArr[2] = '确认为当前套餐关闭该权益吗？';
            swal({
                    title: titleArr[value],
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "确认",
                    showLoaderOnConfirm: true,
                    cancelButtonText: "取消",
            }).then(function(confirm){
                if(confirm.value){
                    $.ajax({
                        url: window.location.pathname + "/" + key,
                        type: "POST",
                        async:false,
                        data: {
                            "status": value,
                            _token: LA.token,
                            _method: 'PUT'
                        },
                        success: function (data) {
                            if (data.status)
                                toastr.success(data.message);
                            else
                                toastr.warning(data.message);
                            setTimeout(function () {
                               $.pjax.reload('#pjax-container');
                            }, 1000);
                        },
                        complete:function(xhr,status) {
                            if (status == 'success')
                                _status = xhr.responseJSON.status;
                        }
                    });
                }else{
                    obj.bootstrapSwitch("state", false);
                }
            });        
            return _status;
        }
    });

SCRIPT;

    }

}